package com.example.fund.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

public class Similarity 
{
	
	public static Double correl(List<Double> dataList,List<Double> dataList1) 
	{   
		if(dataList.size()==0 || dataList1.size()==0)
		{
			return 0d;
		}
		double p = 0d; //最后的皮尔逊相关度系数  
		double n = 0; //操作数的个数  
		double sumX = 0d; //第一个相关数的和  
		double sumY = 0d; //第二个相关数的和  
		double sumSqX = 0d; //第一个相关数的平方和  
		double sumSqY = 0d; //第二个相关数的平方和  
		double sumXY = 0d; //两个相关数乘积的和  

		for(int i = 0;i<Math.min(dataList.size(), dataList1.size());i++){  
			Double x = dataList.get(i);  
			Double y = dataList1.get(i);  
			if(x==null||y==null)
			{
				continue;
			}
			n++;
			sumX += x;  
			sumY += y;  
			sumSqX += Math.pow(x, 2);  
			sumSqY += Math.pow(y,2);
			sumXY += x*y;  
		}  
		double num = n * sumXY - sumX * sumY;   
		double den = Math.sqrt((n * sumSqX - Math.pow(sumX, 2)) * (n * sumSqY - Math.pow(sumY, 2)));   
		p = (den == 0) ? 1 : num / den;   

		return new BigDecimal(p).setScale(2, RoundingMode.HALF_UP).doubleValue();  
	}
}
